package cn.dslcode.security.config.security.rememberme;

import cn.dslcode.security.common.service.UserDetailsServiceImpl;
import cn.dslcode.security.config.security.CustomSecurityConstant;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.RememberMeAuthenticationProvider;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.RememberMeServices;
import org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter;
import org.springframework.security.web.authentication.rememberme.TokenBasedRememberMeServices;
import org.springframework.stereotype.Component;

import javax.servlet.Filter;

/**
 * @author dongsilin
 * @version 2018/4/8.
 */
@Slf4j
@Data
@Component
public class RememberMeAuthenticationConfig {

    private AuthenticationProvider authenticationProvider;
    private RememberMeServices rememberMeServices;
    private Filter filter;

    public RememberMeAuthenticationConfig(
        @Autowired CustomSecurityConstant securityConstant,
        @Autowired UserDetailsServiceImpl userDetailsService
    ) {

        this.authenticationProvider = new RememberMeAuthenticationProvider(securityConstant.getRememberMe().getKey());

        this.rememberMeServices = new TokenBasedRememberMeServices(securityConstant.getRememberMe().getKey(), userDetailsService) {
            {
                setCookieName(securityConstant.getRememberMe().getCookieName());
                // 设置cookie过期时间为2天
                setTokenValiditySeconds(securityConstant.getRememberMe().getTimeSeconds());
                // 设置checkbox的参数名为rememberMe（默认为remember-me），注意如果是ajax请求，参数名不是checkbox的name而是在ajax的data里
                setParameter(securityConstant.getRememberMe().getParameterName());
                setAlwaysRemember(false);
            }
        };
    }

    /**
     * 设置AuthenticationManager，排除循环依赖
     * @param authenticationManager
     * @return
     */
    public Filter getFilterAndSet(AuthenticationManager authenticationManager, AuthenticationSuccessHandler successHandler) {
        if (this.filter == null) {
            this.filter = new RememberMeAuthenticationFilter(authenticationManager, this.rememberMeServices);
        }
        return this.filter;
    }
}